/*
Copyright SecureKey Technologies Inc. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/
package resmgmt

import (
	"testing"

	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/client/iam"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/client/resmgmt"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/core/config"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/ichain_sdk"
	iam2 "git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/providers/iam"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/test/data"
	"github.com/stretchr/testify/assert"
)

func TestResmgmt(t *testing.T) {
	env := data.GetEnvFromFlag()
	assert.NotNil(t, env)
	sdk, err := ichain_sdk.New(config.FromBuilder(env.SdkBuilder()))
	assert.NoError(t, err)
	defer sdk.Close()
	iamClient, err := iam.New(sdk.Context())
	if !assert.NoError(t, err) {
		return
	}
	identity, err := iamClient.CreateSigningIdentity(iam2.WithCert(env.ClientCert()),
		iam2.WithPrivateKey(env.ClientPvk()))

	resCli, err := resmgmt.New(sdk.Context(ichain_sdk.WithIdentity(identity)))
	if !assert.NoError(t, err) {
		return
	}
	// 查询所有链
	resp, err := resCli.QueryChains(resmgmt.WithTargetEndpoints(env.RandInodeName()))
	// 校验链不为空
	if !assert.NoError(t, err) {
		return
	}
	if assert.NotEmpty(t, resp.GetChains()) {
		// 校验链id与配置一致
		var chainIds []string
		for _, chain := range resp.GetChains() {
			chainIds = append(chainIds, chain.GetChainId())
		}
		assert.Contains(t, chainIds, env.ChainId())
	}
	// 测试共识节点查询链配置
	chainCfg, err := resCli.QueryConfigFromConsenser(env.ChainId())
	if !assert.NoError(t, err) {
		return
	}
	assert.NotEmpty(t, chainCfg.IAMs())
	assert.NotEmpty(t, chainCfg.Consensers())

	cfgBlock, err := resCli.QueryConfigBlockFromConsenser(env.ChainId())
	if !assert.NoError(t, err) {
		return
	}
	assert.NotEmpty(t, cfgBlock.GetData().GetData())
}

func TestQueryContract(t *testing.T) {
	env := data.GetEnvFromFlag()
	assert.NotNil(t, env)
	sdk, err := ichain_sdk.New(config.FromBuilder(env.SdkBuilder()))
	assert.NoError(t, err)
	defer sdk.Close()
	iamClient, err := iam.New(sdk.Context())
	if !assert.NoError(t, err) {
		return
	}
	identity, err := iamClient.CreateSigningIdentity(iam2.WithCert(env.AdminCert()),
		iam2.WithPrivateKey(env.AdminKey()))

	resCli, err := resmgmt.New(sdk.Context(ichain_sdk.WithIdentity(identity)))
	if !assert.NoError(t, err) {
		return
	}
	// 测试查询已经安装的合约
	qcResp, err := resCli.QueryInstalledContracts(resmgmt.WithTargetEndpoints(env.RandInodeName()))
	if !assert.NoError(t, err) {
		return
	}
	assert.NotEmpty(t, qcResp.GetContracts())

	icResp, err := resCli.QueryInstantiatedContracts(env.ChainId(), resmgmt.WithTargetEndpoints(env.RandInodeName()))
	if !assert.NoError(t, err) {
		return
	}
	assert.NotEmpty(t, icResp)

}
